"use strict";
//显示combobox的选项值
var taskTypeList = [
    {typeCode:'log',type:'stream',typeName:'日志流水'},
    {typeCode:'request',type:'stream',typeName:'请求流水'},
    {typeCode:'business',type:'stream',typeName:'业务流水'},
    {typeCode:'setFile',type:'file',typeName:'配置文件'},
    {typeCode:'source',type:'file',typeName:'源码文件'},
    {typeCode:'mAgent',type:'quota',typeName:'采集指标'},
    {typeCode:'sdk',type:'quota',typeName:'sdk指标'}
];
// //任务类型字典-3类
var streamDictList = [
    {typeCode:'log',type:'stream',typeName:'日志流水'},
    // {typeCode:'request',type:'stream',typeName:'请求流水'},
    // {typeCode:'business',type:'stream',typeName:'业务流水'},
];
var fileDictList = [
    {typeCode:'setFile',type:'file',typeName:'配置文件'},
    {typeCode:'source',type:'file',typeName:'源码文件'},
];
//状态字典
var statusDict = [
    {value:'1',name:'启用'},
    {value:'0',name:'停用'},
];
//
//任务的dataGrid
var tabIndex = "0";
var taskUpdateOrAdd = "0"; //0|添加  1|更新
var taskQueryParams = {
    nodeCode: '',
    basePath:'',
    hostCode:'',
}
var dataGridTask = {
    $Dg: undefined,
    init: function () {
        //if (this.$Dg == undefined) {
            this.$Dg = $('#Task_dg_' + tabIndex);
            dataGridTask['init_'+tabIndex] = true;
       // }
        if (this.$Dg.length > 0) {
            this.$Dg.datagrid({
                fit:true,
                url: contextPath + "/console/task/queryTaskList",
                queryParams:taskQueryParams,
                columns:[[
                    {field:'taskName',title:'任务名称',width:'15%',align:'center'},
                    {
                        field: 'type', title: '任务类型', width: '15%', align: 'center',
                        formatter: function (value) {
                            for (var i = 0; i < taskTypeList.length; i++) {
                                if (taskTypeList[i].typeCode == value) {
                                    return taskTypeList[i].typeName;
                                }
                            }
                            return value;
                        }
                    },
                    {
                        field: 'status', title: '状态', width: '10%', align: 'center',
                        formatter: function (value) {
                            for (var i = 0; i < statusDict.length; i++) {
                                if (statusDict[i].value == value) return statusDict[i].name;
                            }
                            return value;
                        },
                    },
                    {field:'value',title:'任务内容',width:'44%',align:'center'}
                ]],
                toolbar: [{
                    id:"easyuiAddBtn",
                    text: '新增',
                    iconCls: 'icon-add',
                    plain:true,
                    handler: function () {
                        dataGridTask.dialogOpen("0");
                    }
                },{
                    id:"easyuiUptBtn",
                    text: '编辑',
                    iconCls: 'icon-edit',
                    plain:true,
                    handler: function () {
                        dataGridTask.$Dg = $("#Task_dg_"+tabIndex);
                        var row = dataGridTask.$Dg.datagrid('getSelected');
                        if (row) {
                            //console.log(row);
                            dataGridTask.dialogOpen("1");
                        }else{
                            apexLayer.Warn('请先选择一条记录，才能进行修改操作！');
                        }

                    }
                },{
                    id:"easyuiDelBtn",
                    text: '删除',
                    iconCls: 'icon-remove',
                    plain:true,
                    handler: function () {
                        // 获取选中的行
                        dataGridTask.$Dg = $("#Task_dg_"+tabIndex);
                        var row = dataGridTask.$Dg.datagrid('getSelected');
                        if (row) {
                            apexLayer.Confirm("您确认删除任务吗？",
                                "删除任务",
                                "确认",
                                "取消",
                                function () {
                                    Ajax({
                                        url: contextPath + "/console/task/delete",
                                        isMask: true,
                                        data: {
                                            "hostCode": taskQueryParams.hostCode,
                                            "nodeCode": taskQueryParams.nodeCode,
                                            "taskCode": row.taskCode
                                        },
                                        success: function (data) {
                                            if (data.code>0) {
                                                apexLayer.Msg(data.note, 1000, function () {
                                                    dataGridTask.$Dg = $("#Task_dg_"+tabIndex);
                                                    dataGridTask.$Dg.datagrid("reload");
                                                });
                                            } else {
                                                apexLayer.Error(data.note);
                                            }
                                        }
                                    });
                                }
                            );
                        } else {
                            apexLayer.Warn('请先选择一条记录，才能进行删除操作！');
                        }
                    }
                }],
                rownumbers: true,
                rownumberWidth: 70,
                singleSelect: true,
                emptyMsg:'暂无数据',
                loadMsg:"",
                onLoadSuccess:function(data){

                },
                onLoadError:function(){

                }
            });
        }
    },
    /**
     * 渲染任务的两个dialog
     */
    renderTaskDialog:function(){

        /**
         * 模板任务展示界面
         */
        $("#templateTask-dlg").dialog({
            title: '任务管理',
            width: 800,
            height: 500,
            closed: true,
            cache: false,
            shadow: false,
            modal: true,
            onOpen:function () {
                tabIndex = 0;
                if(!dataGridTask['init_'+tabIndex]){
                    dataGridTask.init();
                }else{
                    dataGridTask.$Dg = $("#Task_dg_"+tabIndex);
                    dataGridTask.$Dg.datagrid("reload");
                }
                $('#tt').tabs("select",0);
            },
            onClose:function(){

            }
        });

        /**
         * 任务记录操作界面
         */
        $("#task-add-dlg").dialog({
            title: '任务操作',
            width: 600,
            height: 'auto',
            closed: true,
            cache: false,
            shadow: false,
            modal: true,
            buttons: [{
                text: '保存',
                iconCls: 'icon-save',
                handler: function () {
                    $.messager.progress();
                    var url = "";
                    if(taskUpdateOrAdd=="0"){
                        url = "/console/task/add";
                    }else if(taskUpdateOrAdd=="1"){
                        url = "/console/task/update";
                    }
                    $('#taskDataForm').form('submit',{
                        url:contextPath+url,
                        onSubmit: function(param){
                            if (!$(this).form('validate')) {
                                $.messager.progress('close');
                                return false;
                            }

                            var type = $('#type').combobox("getValue");

                            var attrs = $("#form_"+type).serializeArray();
                            if($("#attr_"+type) && $("#attr_"+type).length>0 && !$("#attr_"+type).is(":hidden")){
                                var attr = {};
                                if(!$("#form_"+type).form('validate')){
                                    $.messager.progress('close');
                                    return false;
                                }
                                attrs.forEach(function(obj,index,arr){
                                    attr[obj.name+""] = obj.value;
                                });
                                param.attribute = JSON.stringify(attr);
                            }else{
                                param.attribute = null;
                            }
                            param.nodeCode = taskQueryParams.nodeCode;
                            param.hostCode = taskQueryParams.hostCode;
                        },
                        success:function(data){
                            $.messager.progress('close');
                            var obj = JSON.parse(data);
                            if (obj.code>0) {
                                apexLayer.Msg(obj.note, 1000, function () {
                                    dataGridTask.$Dg = $("#Task_dg_"+tabIndex);
                                    dataGridTask.$Dg.datagrid("reload");
                                    $("#task-add-dlg").dialog('close');
                                });
                            } else {
                                apexLayer.Error(obj.note);
                            }
                        }
                    });
                }
            }],
            onOpen:function () {
                $("#taskDataForm").form("clear");
                $("form[id^='form_']").form("clear");
                $("table[id^='attr_']").addClass("hide");
                if(taskUpdateOrAdd=="0"){
                    $("#taskDataForm").form("clear");
                    $("#taskDataForm #value").val("$");
                }else if(taskUpdateOrAdd=="1"){
                    dataGridTask.$Dg = $("#Task_dg_"+tabIndex);
                    var row = dataGridTask.$Dg.datagrid("getSelected");
                    if(row){
                        for (var key in row) {
                            var $element = $("#taskDataForm #"+key);
                            if(key=="attr"){
                                if(row[key]){
                                    var attributeObj = JSON.parse(row[key]);
                                    if(attributeObj && Object.keys(attributeObj).length >0){
                                        var keys = Object.keys(attributeObj);
                                        keys.forEach(function(attrKey,index,arr){
                                            var $attrElement = $("#"+attrKey);
                                            if ($attrElement.hasClass("easyui-textbox")) {
                                                $attrElement.textbox('setValue', attributeObj[attrKey]);
                                            } else if ($attrElement.hasClass("easyui-combobox")) {
                                                $attrElement.combobox('setValue', attributeObj[attrKey]);
                                            } else {
                                                $attrElement.val(attributeObj[key]);
                                            }
                                        });
                                    }
                                }
                            }else if ($element.hasClass("easyui-textbox")) {
                                $element.textbox('setValue', row[key]);
                            } else if ($element.hasClass("easyui-combobox")) {
                                $element.combobox('setValue', row[key]);
                            } else {
                                $element.val(row[key]);
                            }
                        }
                    }
                }
            },
            onClose: function () {
                $("#taskDataForm").form("clear");
            }
        });

        /**
         * 流水和文件tab
         */
        $('#tt').tabs({
            onSelect:function(title,index){
                tabIndex = index;
                var group = "stream";
                if(index==1){
                    group = "file";
                }
                //taskQueryParams.group = group;
                if(!dataGridTask['init_'+tabIndex]){
                    dataGridTask.init();
                }else{
                    dataGridTask.$Dg = $("#Task_dg_"+tabIndex);
                    dataGridTask.$Dg.datagrid("reload");
                }
            }
        });
    },
    /**
     * 打开操作任务的界面
     * @param updateOrAdd  0|新增  1|新增
     */
    dialogOpen:function(updateOrAdd){
        var tab = $('#tt').tabs('getSelected');
        var index = $('#tt').tabs('getTabIndex',tab);
        var group = "stream";
        var selectValue = "log";
        if(index==1){
            group = "file";
            selectValue = "setFile";
        }
        $('#type').combobox("clear");
        $('#type').combobox({
            valueField: 'typeCode',
            textField: 'typeName',
            data:index==1?fileDictList:streamDictList,
            onSelect:function(record){
                $("table[id^='attr_']").addClass("hide");
                if($("#attr_"+record.typeCode) && $("#attr_"+record.typeCode).length>0){
                    $("#attr_"+record.typeCode).removeClass("hide");
                }
            }
        });
        taskUpdateOrAdd = updateOrAdd;
        $("#task-add-dlg").dialog("open");
    },
};
